class SidePanelController {
  constructor() {
    this.terminals = [];
    this.currentTab = null;
    this.init();
  }

  async init() {
    console.log('[SidePanel] 初始化开始');
    await this.getCurrentTab();
    await this.loadTerminals();
    this.setupEventListeners();
    this.setupMessageListener();
    console.log('[SidePanel] 初始化完成');
  }

  async getCurrentTab() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    this.currentTab = tab;
    console.log('[SidePanel] 当前标签页:', tab?.url);
  }

  async loadTerminals() {
    console.log('[SidePanel] 开始加载终端');
    try {
      // 先尝试注入content script
      await chrome.scripting.executeScript({
        target: { tabId: this.currentTab.id },
        files: ['content.js']
      });
      
      // 等待一下让content script初始化
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const response = await chrome.tabs.sendMessage(this.currentTab.id, {
        type: 'GET_TERMINALS'
      });
      
      this.terminals = response || [];
      console.log('[SidePanel] 检测到终端数量:', this.terminals.length);
      this.renderTerminals();
      this.updateStatus();
    } catch (error) {
      console.log('[SidePanel] 加载终端失败:', error);
      this.updateStatus('未检测到终端或页面不支持', 'error');
    }
  }

  renderTerminals() {
    const container = document.getElementById('terminals-container');
    container.innerHTML = '';

    if (this.terminals.length === 0) {
      container.innerHTML = '<p>未检测到终端</p>';
      return;
    }

    this.terminals.forEach(terminalId => {
      const terminalDiv = document.createElement('div');
      terminalDiv.className = 'terminal-item';
      terminalDiv.innerHTML = `
        <h4>终端: ${terminalId}</h4>
        <input type="text" class="command-input" placeholder="输入命令..." data-terminal="${terminalId}">
        <button class="send-btn" data-terminal="${terminalId}">发送</button>
        <div class="output-area" id="output-${terminalId}"></div>
      `;
      container.appendChild(terminalDiv);
    });
  }

  setupEventListeners() {
    // 发送命令按钮
    document.addEventListener('click', async (e) => {
      if (e.target.classList.contains('send-btn')) {
        const terminalId = e.target.dataset.terminal;
        const input = document.querySelector(`input[data-terminal="${terminalId}"]`);
        
        if (input) {
          const command = input.value.trim();
          if (command) {
            await this.sendCommand(terminalId, command);
            input.value = '';
          }
        }
      }
      
      // 快速命令按钮
      if (e.target.classList.contains('auto-command-btn')) {
        const command = e.target.dataset.command;
        if (this.terminals.length > 0) {
          await this.sendCommand(this.terminals[0], command);
        }
      }
    });

    // 回车发送命令
    document.addEventListener('keypress', async (e) => {
      if (e.key === 'Enter' && e.target.classList.contains('command-input')) {
        const terminalId = e.target.dataset.terminal;
        const command = e.target.value.trim();
        
        if (command) {
          await this.sendCommand(terminalId, command);
          e.target.value = '';
        }
      }
    });

    // 刷新检测按钮
    document.getElementById('refresh-btn').addEventListener('click', async () => {
      console.log('[SidePanel] 点击刷新检测按钮');
      this.updateStatus('正在刷新检测...', 'success');
      await this.loadTerminals();
    });
  }

  async sendCommand(terminalId, command) {
    console.log('[SidePanel] 发送命令:', command, '到终端:', terminalId);
    try {
      const response = await chrome.tabs.sendMessage(this.currentTab.id, {
        type: 'SEND_COMMAND',
        terminalId: terminalId,
        command: command
      });

      console.log('[SidePanel] 命令响应:', response);
      if (response && response.success) {
        this.updateStatus(`命令已发送: ${command}`, 'success');
        this.addToOutput(terminalId, `> ${command}`);
      } else {
        this.updateStatus('发送命令失败', 'error');
      }
    } catch (error) {
      console.log('[SidePanel] 发送命令错误:', error);
      this.updateStatus('发送命令时出错', 'error');
    }
  }

  setupMessageListener() {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.type === 'OUTPUT_ANALYSIS') {
        console.log('[SidePanel] 收到输出分析:', request.data);
        this.displayAnalysis(request.data);
      }
    });
  }

  displayAnalysis(analysis) {
    const analysisOutput = document.getElementById('analysis-output');
    const analysisContent = document.getElementById('analysis-content');
    
    analysisOutput.style.display = 'block';
    
    let commandResultHtml = '';
    if (analysis.commandResult) {
      const result = analysis.commandResult;
      commandResultHtml = `<div><strong>命令结果:</strong> ${result.command} (${result.type})</div>`;
      
      if (result.type === 'file_list' && result.files) {
        commandResultHtml += `<div>文件数量: ${result.files.length}</div>`;
        commandResultHtml += '<div>文件列表: ' + result.files.slice(0, 5).map(f => f.name).join(', ');
        if (result.files.length > 5) commandResultHtml += '...';
        commandResultHtml += '</div>';
      } else if (result.type === 'current_directory') {
        commandResultHtml += `<div>当前目录: ${result.directory}</div>`;
      } else if (result.type === 'current_user') {
        commandResultHtml += `<div>当前用户: ${result.user}</div>`;
      } else if (result.type === 'process_list' && result.processes) {
        commandResultHtml += `<div>进程数量: ${result.processes.length}</div>`;
      }
    }
    
    const analysisItem = document.createElement('div');
    analysisItem.innerHTML = `
      <div><strong>时间:</strong> ${new Date(analysis.timestamp).toLocaleTimeString()}</div>
      <div><strong>终端:</strong> ${analysis.terminalId}</div>
      <div><strong>检测到的模式:</strong> ${analysis.patterns.join(', ') || '无'}</div>
      ${commandResultHtml}
      ${analysis.nextAction ? `<div><strong>自动执行:</strong> ${analysis.nextAction}</div>` : ''}
      <hr>
    `;
    
    analysisContent.insertBefore(analysisItem, analysisContent.firstChild);
    
    // 限制显示的分析记录数量
    while (analysisContent.children.length > 10) {
      analysisContent.removeChild(analysisContent.lastChild);
    }
  }

  addToOutput(terminalId, text) {
    const outputDiv = document.getElementById(`output-${terminalId}`);
    if (outputDiv) {
      const line = document.createElement('div');
      line.textContent = text;
      outputDiv.appendChild(line);
      outputDiv.scrollTop = outputDiv.scrollHeight;
    }
  }

  updateStatus(message = '', type = 'success') {
    const statusDiv = document.getElementById('status');
    
    if (!message) {
      message = this.terminals.length > 0 
        ? `检测到 ${this.terminals.length} 个终端` 
        : '未检测到终端';
    }
    
    statusDiv.textContent = message;
    statusDiv.className = `status ${type}`;
  }
}

// 初始化侧边栏控制器
document.addEventListener('DOMContentLoaded', () => {
  new SidePanelController();
});